package redis

import (
	"WebFacade/log"
	"WebFacade/tools"
	"github.com/go-redis/redis"
	"strconv"
)

var client *redis.Client

var (
	host     = "127.0.0.1"
	port     = 6379
	password = ""
	dbname   = 0
	poolsize = 40
	env      = "release"
)

func InitDefault() {

}

func InitRedis(_host string, _port int, _password string, _dbname int, _poolsize int, _env string) {
	host = _host
	port = _port
	password = _password
	dbname = _dbname
	poolsize = _poolsize
	env = _env
	var err error
	client, err = newClient()
	if err != nil {
		panic(err)
	}
}

func newClient() (*redis.Client, error) {
	client := redis.NewClient(&redis.Options{
		Addr:     host + ":" + strconv.Itoa(port),
		Password: password,
		DB:       dbname,
		PoolSize: poolsize,
	})

	_, err := client.Ping().Result()
	if err != nil {
		err = log.FatalLog(log.ErrorDBRedis, map[string]interface{}{
			"host":     host,
			"port":     port,
			"password": password,
			"dbname":   dbname,
			"poolsize": poolsize,
		}, err)
		return nil, err
	}
	return client, nil
}

func GetClient() *redis.Client {
	return getClient()
}

func getClient() *redis.Client {
	if client == nil {
		client, _ = newClient()
	}
	return client
}

func StopRedis() {
	if client != nil {
		client.Close()
	}
}

func generateRedisKey(v ...string) string {
	var keyPrefix = "super_kf"
	vl := append([]string{keyPrefix}, v...)
	return tools.KeyEncode(":", vl...)
}
